<template>
  <div class="p-2">
    <Forms ref="subForm" :data-from="formData" :list="pageSetting.TestLog.search" name="TestLog" :sub-loading="tableLoading" />
    <div class="flex">
      <div :style="{ width: drawer ? '50%' : '100%' }">
        <Table
          ref="main_Table"
          :column-list="mainTableColumn"
          :get-height="getHeight"
          :loading="tableLoading"
          name="TestLog"
          :style="{ height: `${getHeight}px` }"
          :tables="tables"
        />
      </div>
      <div v-show="drawer" class="tab-content" style="width: 50%">
        <el-tabs v-model="tabName" v-loading="tabLoading" type="card" @tab-click="handleClick">
          <el-tab-pane v-for="(item, index) of tabList" :key="index" :label="item.title" :name="item.name">
            <div v-if="item.name === 'four'">
              <Table
                ref="sql_Table"
                :column-list="sqlTableColumn"
                :get-height="`${getHeight - 30}`"
                name="TestLog"
                :style="{ height: `${getHeight - 30}px` }"
                :tables="sqlTables"
              />
            </div>
            <div v-else-if="item.name === 'thrid'" :style="{ height: `${getHeight - 100}px` }">
              <CodeEditor v-model="vuiCodevalue" :height="getHeight - 100" />
            </div>
            <div v-else :style="{ height: `${getHeight - 100}px` }">
              <CodeEditor v-model="vuiCodevalue" :cm-options="jsOptions" :height="getHeight - 100" />
            </div>
          </el-tab-pane>
        </el-tabs>
        <vui-icon class="back" icon="arrow-right-circle-fill" @click="backTab" />
      </div>
    </div>
    <el-dialog v-model="detailsDialog" :title="translateTitle('Dams.ApplicationInterface.Sql详情')" width="80%">
      <el-form v-if="detailsDialog" ref="form" label-position="top" :model="sqlForm">
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.执行SQL')">
          <CodeEditor ref="VuiCodeEditor_SQL" v-model="sqlForm.SQL_CONTENT" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.SQL参数')">
          <CodeEditor ref="VuiCodeEditor_PARAMS_S" v-model="sqlForm.PARAMS" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.结果集')">
          <CodeEditor ref="VuiCodeEditor_RESULTS_S" v-model="sqlForm.RESULTS" />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import { Mixin } from '@/common/minxin/Mixin'
  import { GFCD } from '@/utils/utils'
  import TestLog from '../../components/json/TestLog'
  import { getList } from '../../api/home.js'
  import Table from '../../components/table.vue'
  import Forms from '../../components/forms'
  import debounce from 'lodash/debounce'
  import { translateTitle } from '@/utils/i18n'
  import CodeEditor from '../../components/codeEditor'
  const beautify_js = require('js-beautify')
  // import isArray from 'lodash/isArray'
  export default {
    name: 'TestLog',
    components: { Table, Forms, CodeEditor },
    mixins: [Mixin],
    data() {
      return {
        detailsDialog: false,
        sqlForm: {},
        // 选项卡列表
        tabList: [
          { name: 'first', title: translateTitle('Dams.ApplicationInterface.请求消息') },
          { name: 'second', title: translateTitle('Dams.ApplicationInterface.响应消息') },
          { name: 'thrid', title: translateTitle('Dams.ApplicationInterface.异常消息') },
          { name: 'four', title: translateTitle('Dams.ApplicationInterface.SQL日志') },
          { name: 'five', title: '其他' },
        ],
        tabLoading: false,
        tabName: 'first',
        pageSetting: {
          TestLog: { search: {} },
        },
        jsOptions: {
          tabSize: 1,
          smartIndent: true,
          indetUnit: 1,
          styleActiveLine: true,
          lineNumbers: true,
          line: true,
          theme: 'dracula',
          foldGutter: true,
          lineWrapping: true,
          autoRefresh: true,
          mode: 'text/javascript',
        },
        drawer: false,
        configSetting: {},
        apiParameter: {},
        show: false,
        formData: {},
        collapseActive: ['1'],
        tables: {
          tableList: [],
          count: 0,
          pageSize: 150,
          limit: 1,
          name: 'TestLog',
          operation: true,
          formatting: false,
        },
        sqlTables: {
          tableList: [],
          count: 0,
          pageSize: 50,
          limit: 1,
          name: 'TestLogSql',
          operation: true,
          formatting: false,
        },
        sqlTableColumn: [
          {
            porp: 'SQL_INDEX',
            label: translateTitle('Dams.ApplicationInterface.执行序号'),
          },
          {
            porp: 'SQL_TYPE',
            label: 'SQL类型',
          },
          {
            porp: 'SQL_CONTENT',
            label: translateTitle('Dams.ApplicationInterface.执行SQL'),
          },
          {
            porp: 'PARAMS',
            label: translateTitle('Dams.ApplicationInterface.SQL参数'),
          },
          {
            porp: 'ROWS',
            label: translateTitle('Dams.ApplicationInterface.受影响行'),
          },
          {
            porp: 'EXEC_TIME',
            label: translateTitle('Dams.ApplicationInterface.实行用时'),
          },
          {
            porp: 'RESULTS',
            label: translateTitle('Dams.ApplicationInterface.结果集'),
          },
        ],
        clientHeight: 0,
        vuiCodevalue: '',
        tableLoading: false,
        logItem: {},
        unsubs: [],
      }
    },
    computed: {
      getHeight() {
        return `${this.clientHeight - 220}`
      },
      mainTableColumn() {
        if (this.pageSetting.TestLog.dialog) {
          let arr = this.pageSetting.TestLog.dialog.form.field
          let newArr = []
          arr.forEach((v) => {
            if (v.type != 'button' && v.type != 'line' && !v.tableHidden && v.type != 'userPeriod') {
              newArr.push({
                label: v.label,
                porp: v.name,
                type: v.type,
              })
            }
            if (v.type == 'userPeriod') {
              newArr.push({
                label: v.label,
                porp: v.name.split(',')[0] + ',' + v.name.split(',')[1],
                type: v.type,
              })
            }
          })
          return newArr
        } else {
          return []
        }
      },
    },
    async created() {
      await this.init()
      console.log(this.$route.query)
      if (this.$route.query) {
        this.apiParameter = this.$route.query
        if (this.apiParameter && Object.keys(this.apiParameter).length > 0) {
          for (const key in this.apiParameter) {
            const element = this.apiParameter[key]
            this.formData[key] = element
          }
          this.onSubmit([this.formData])
        }
      }
    },
    unmounted() {
      this.unsubs.forEach((v) => {
        this.$unsub(v)
      })
    },
    methods: {
      backTab() {
        this.drawer = false
      },
      formateCode(code) {
        const formate = beautify_js(code, {
          indent_size: 2,
          html: {
            end_with_newline: true,
            js: {
              indent_size: 2,
            },
            css: {
              indent_size: 2,
            },
          },
          css: {
            indent_size: 1,
          },
          js: {
            'preserve-newlines': true,
          },
        })
        return formate
      },
      translateTitle,
      handleClick() {
        switch (this.tabName) {
          case 'first':
            this.vuiCodevalue = this.tabList[0].value
            break
          case 'second':
            this.vuiCodevalue = this.tabList[1].value
            break
          case 'thrid':
            this.vuiCodevalue = this.tabList[2].value
            break
          case 'five':
            this.vuiCodevalue = this.tabList[4].value
            break
          default:
            break
        }
      },
      validateJSON(data) {
        if (typeof data == 'string') {
          try {
            var obj = JSON.parse(data)
            if (typeof obj == 'object' && obj) {
              return true
            } else {
              return false
            }
          } catch (e) {
            return false
          }
        }
      },
      jsonFormatting() {
        // this.formatting(this.validateJSON)
        if (!this.validateJSON(this.vuiCodevalue))
          return this.$baseMessage(translateTitle('Dams.ApplicationInterface.JSON格式错误'), 'error')
            ? JSON.stringify(JSON.parse(this.vuiCodevalue), null, 4)
            : translateTitle('Dams.ApplicationInterface.暂无数据')
      },
      windowResize: debounce(function () {
        this.clientHeight = document.documentElement.clientHeight
      }, 100),
      async onSubmit(p) {
        let sub = p ? JSON.parse(JSON.stringify(p)) : []
        let obj = {
          '#LIMIT#': this.tables.limit,
          '#PAGE_SIZE#': this.tables.pageSize,
          ...sub[0],
        }
        if (p.length > 0 && p[0].DATE_TIME) {
          delete obj.DATE_TIME
          obj.DATE_TIME_START = p[0].DATE_TIME[0]
          obj.DATE_TIME_END = p[0].DATE_TIME[1]
        }
        this.tableLoading = true
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify(obj),
          method: this.pageSetting.TestLog.search.form.method,
        })
        console.log(res)
        this.tableLoading = false
        this.tables.tableList = res.data.data.data
        this.tables.count = res.data.data.count
      },
      //查询msg日志
      async getMsg(REQUEST_UUID) {
        const p = JSON.parse(JSON.stringify(this.formData))
        let obj = { ...p, '#LIMIT#': 1, '#PAGE_SIZE#': 9999, REQUEST_UUID }
        if (obj.DATE_TIME) {
          delete obj.DATE_TIME
          obj.DATE_TIME_START = this.formData.DATE_TIME[0]
          obj.DATE_TIME_END = this.formData.DATE_TIME[1]
        }
        this.tabLoading = true
        let method = this.pageSetting.TestLog.msgMethod
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify(obj),
          method: method,
        })
        this.tabLoading = false
        const request = res.data.data
        this.msgs = request.data[0]
        this.tabList.forEach((row) => {
          console.log(row)
          if (row.name == 'first') {
            row.value = request.data[0] ? this.formateCode(request.data[0]?.REQUEST_MSG) : ''
          }
          if (row.name == 'second') {
            row.value = request.data[0] ? this.formateCode(request.data[0]?.RESPONSE_MSG) : ''
          }
          if (row.name == 'five') {
            row.value = request.data[0] ? this.formateCode(request.data[0]?.PRINT_LOG_INFO) : ''
          }
          if (row.name == 'thrid') {
            row.value = ''
            if (request.data.length > 0) {
              for (let index = 0; index < request.data.length; index++) {
                const element = request.data[index]
                row.value = `${row.value}\n${element.EXCEPTION_MSG}`
              }
            } else {
              row.value = request.data[0]?.EXCEPTION_MSG
            }
          }
        })
        console.log(this.tabList)
        switch (this.tabName) {
          case 'first':
            this.vuiCodevalue = this.tabList[0].value || translateTitle('Dams.ApplicationInterface.暂无数据')
            break
          case 'second':
            this.vuiCodevalue = this.tabList[1].value || translateTitle('Dams.ApplicationInterface.暂无数据')
            break
          case 'thrid':
            this.vuiCodevalue = this.tabList[2].value || translateTitle('Dams.ApplicationInterface.暂无数据')
            break
          case 'five':
            this.vuiCodevalue = this.tabList[3].value || translateTitle('Dams.ApplicationInterface.暂无数据')
            break
          default:
            break
        }
      },
      //查询sql日志
      async getSql(REQUEST_UUID, limit, pageSize) {
        const p = JSON.parse(JSON.stringify(this.formData))
        if (p.DATE_TIME) {
          delete p.DATE_TIME
          p.DATE_TIME_START = this.formData.DATE_TIME[0]
          p.DATE_TIME_END = this.formData.DATE_TIME[1]
        }
        let obj = { ...p, '#LIMIT#': limit || 1, '#PAGE_SIZE#': pageSize || 50, REQUEST_UUID }
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify(obj),
          method: this.pageSetting.TestLog.sqlMethod,
        })
        this.sqlTables.tableList = res.data.data.data
        this.sqlTables.count = res.data.data.count
      },
      eventInit() {
        //搜索事件
        this.$sub(`TestLog_forms_on_search`, (data_arr) => {
          this.formData = data_arr[0]
          this.tables.limit = 1
          this.onSubmit(data_arr)
        })
        this.$sub('TestLog_Table_clickOne_TestLogSql', (data_arr) => {
          this.sqlForm = data_arr[0]
          this.detailsDialog = true
        })
        this.$sub('TestLog_Table_on_TestLogSql', (page_arr) => {
          this.sqlTables.limit = page_arr[0].limit
          this.sqlTables.pageSize = page_arr[0].pageSize
          this.getSql(this.logItem.REQUEST_UUID, page_arr[0].limit, page_arr[0].pageSize)
        })
        this.unsubs.push(`TestLog_forms_on_search`)
        this.$sub(`TestLog_Table_clickOne_TestLog`, (page_arr) => {
          this.logItem = page_arr[0]
          this.getSql(page_arr[0].REQUEST_UUID)
          this.getMsg(page_arr[0].REQUEST_UUID)
          this.drawer = true
        })
        this.unsubs.push(`TestLog_Table_clickOne_TestLog`)
        this.$sub(`TestLog_Table_on_TestLog`, (page_arr) => {
          // console.log(11111, this.formData)
          this.tables.limit = page_arr[0].limit
          this.tables.pageSize = page_arr[0].pageSize
          this.onSubmit([this.formData])
        })
        this.unsubs.push(`TestLog_Table_on_TestLog`)
      },
      async init() {
        this.configSetting = GFCD('dams')
        let res = await this.getSubsystemData()
        let list = []
        res.forEach((item) => {
          list.push({ CODE: item.CODE, LABEL: item.LABEL })
        })
        console.log(TestLog)
        // this.nowJsonData().then((data) => {
        this.pageSetting = TestLog
        let listField = this.pageSetting.TestLog.search.form.field
        listField.forEach((item) => {
          if (item.name == 'SUB_SYSTEM') {
            item.options = list
          }
        })
        this.show = true
        this.windowResize()
        this.eventInit()
      },
      //获取子系统下拉数据
      async getSubsystemData() {
        let method = 'dams.handle.flow.query.options'
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify({ '#LIMIT#': 1, '#PAGE_SIZE#': 9999 }),
        })
        return res.data.SUB_SYSTEM.data
      },
    },
  }
</script>
<style lang="scss">
  .tab-content {
    position: relative;
    .back {
      position: absolute;
      right: 0;
      top: -18px;
      cursor: pointer;
    }
    :deep() {
      .el-tabs__nav-prev,
      .el-tabs__nav-next {
        line-height: 20px;
      }
    }
  }
</style>
